package com.yc.cloud.admin.service.impl;

import cn.hutool.json.JSONUtil;
import com.yc.cloud.admin.config.SipServerProperties;
import com.yc.cloud.admin.dto.request.SipDeviceQueryReqDTO;
import com.yc.cloud.admin.service.SipServerService;
import com.yc.cloud.admin.vo.SipDeviceListVo;
import com.yc.cloud.admin.vo.SipDeviceVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.ArrayList;

/**
 * SIP信令服务器API服务实现类
 *
 * @author kinggu
 * @since 2025-09-09
 */
@Slf4j
@Service
public class SipServerServiceImpl implements SipServerService {

    @Resource
    private SipServerProperties sipServerProperties;

    @Resource(name = "sipServerWebClient")
    private WebClient sipServerWebClient;

    @Override
    public SipDeviceListVo queryDevices(SipDeviceQueryReqDTO queryReqDTO) {
        try {
            log.info("查询SIP设备列表: pageNum={}, pageSize={}, keyword={}", 
                    queryReqDTO.getPageNum(), queryReqDTO.getPageSize(), queryReqDTO.getKeyword());

            String responseBody = sipServerWebClient.get()
                    .uri(uriBuilder -> {
                        var builder = uriBuilder
                                .path("/device/query/devices")
                                .queryParam("page", queryReqDTO.getPageNum())
                                .queryParam("count", queryReqDTO.getPageSize());
                        
                        if (queryReqDTO.getKeyword() != null && !queryReqDTO.getKeyword().trim().isEmpty()) {
                            builder.queryParam("query", queryReqDTO.getKeyword().trim());
                        }
                        
                        return builder.build();
                    })
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();

            if (responseBody != null) {
                // 解析SIP信令服务器响应格式
                JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
                Integer code = jsonResponse.getInt("code");
                String msg = jsonResponse.getStr("msg");
                
                if (code == 0) {  // 成功响应码为0
                    SipDeviceListVo deviceListVo = JSONUtil.toBean(jsonResponse.getStr("data"), SipDeviceListVo.class);
                    log.info("查询SIP设备列表成功: total={}", 
                            deviceListVo != null ? deviceListVo.getTotal() : 0);
                    return deviceListVo;
                } else {
                    log.error("查询SIP设备列表失败: code={}, msg={}", code, msg);
                }
            } else {
                log.error("查询SIP设备列表失败: 响应为空");
            }
        } catch (Exception e) {
            log.error("查询SIP设备列表异常: pageNum={}, pageSize={}, keyword={}", 
                    queryReqDTO.getPageNum(), queryReqDTO.getPageSize(), queryReqDTO.getKeyword(), e);
        }
        
        // 返回空结果
        SipDeviceListVo emptyResult = new SipDeviceListVo();
        emptyResult.setTotal(0);
        emptyResult.setList(new ArrayList<>());
        return emptyResult;
    }

    @Override
    public SipDeviceVo getDeviceById(String deviceId) {
        try {
            log.info("查询SIP设备详情: deviceId={}", deviceId);

            String responseBody = sipServerWebClient.get()
                    .uri(uriBuilder -> uriBuilder
                            .path("/device/query/{deviceId}")
                            .build(deviceId))
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();

            if (responseBody != null) {
                // 解析SIP信令服务器响应格式
                JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
                Integer code = jsonResponse.getInt("code");
                String msg = jsonResponse.getStr("msg");
                
                if (code == 0) {  // 成功响应码为0
                    SipDeviceVo deviceVo = JSONUtil.toBean(jsonResponse.getStr("data"), SipDeviceVo.class);
                    log.info("查询SIP设备详情成功: deviceId={}", deviceId);
                    return deviceVo;
                } else {
                    log.error("查询SIP设备详情失败: deviceId={}, code={}, msg={}", 
                            deviceId, code, msg);
                }
            } else {
                log.error("查询SIP设备详情失败: deviceId={}, 响应为空", deviceId);
            }
        } catch (Exception e) {
            log.error("查询SIP设备详情异常: deviceId={}", deviceId, e);
        }
        
        return null;
    }

    @Override
    public boolean controlPtz(String deviceId, String channel, String command, Integer horizonSpeed, Integer verticalSpeed, Integer zoomSpeed) {
        try {
            log.info("控制PTZ设备: deviceId={}, channel={}, command={}, horizonSpeed={}, verticalSpeed={}, zoomSpeed={}", 
                    deviceId, channel, command, horizonSpeed, verticalSpeed, zoomSpeed);

            String responseBody = sipServerWebClient.get()
                    .uri(uriBuilder -> uriBuilder
                            .path("/front-end/ptz/{deviceId}/{channel}")
                            .queryParam("command", command)
                            .queryParam("horizonSpeed", horizonSpeed != null ? horizonSpeed : 0)
                            .queryParam("verticalSpeed", verticalSpeed != null ? verticalSpeed : 0)
                            .queryParam("zoomSpeed", zoomSpeed != null ? zoomSpeed : 0)
                            .build(deviceId, channel))
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();

            if (responseBody != null) {
                // 解析SIP信令服务器响应格式
                JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
                Integer code = jsonResponse.getInt("code");
                String msg = jsonResponse.getStr("msg");
                
                if (code == 0) {  // 成功响应码为0
                    log.info("PTZ控制成功: deviceId={}, command={}", deviceId, command);
                    return true;
                } else {
                    log.error("PTZ控制失败: deviceId={}, command={}, code={}, msg={}", 
                            deviceId, command, code, msg);
                }
            } else {
                log.error("PTZ控制失败: deviceId={}, command={}, 响应为空", deviceId, command);
            }
        } catch (Exception e) {
            log.error("PTZ控制异常: deviceId={}, command={}", deviceId, command, e);
        }
        
        return false;
    }
}